package app

import (
	"encoding/json"
	"fmt"
	"golang-blog/helper"
	"golang-blog/infrastructure/databases"
	"golang-blog/infrastructure/log"
	"golang-blog/models"

	"github.com/gin-gonic/gin"
	"github.com/pkg/errors"
)

// tag handler
type TagInfoQueryReq struct {
	TagID       int    `json:"tag_id"`
	TagLikeName string `json:"tag_name"`
}
type TagInfoQueryResp struct {
	ID          int    `json:"id"`
	TagName     string `json:"tag_name"`     // 标签名
	CitedNum    int    `json:"cited_num"`    // 被引次数
	Description string `json:"descrtiption"` // 标签描述
}
type TagListQueryReq struct {
	TagLikeName string `json:"tag_name"`  // 可以模糊查询的名字
	Page        int    `json:"page"`      // 用于分页
	PageSize    int    `json:"page_size"` // limit
}
type TagListQueryResp struct {
	Tags         []TagInfoQueryResp `json:"tag_list"`
	Page         int                `json:"page"`           //当前页索引，从1开始计数
	Count        int                `json:"count"`          //每页的实际记录条数，可能小于需要获取的条数
	TotalPageNum int                `json:"total_page_num"` //总页数
}

func GetTagList() gin.HandlerFunc {
	return func(c *gin.Context) {
		tqr := new(TagListQueryReq)
		if err := c.ShouldBindJSON(tqr); err != nil {
			helper.SetHttpMsgResp(c, helper.HttpCodeValidateFail, helper.Translate(err))
			return
		}
		nameSql := fmt.Sprintf(" tags.tag_name LIKE '%%%s%%'", tqr.TagLikeName)
		baseSql := fmt.Sprintf("from tags where %s", nameSql)
		limitSql := fmt.Sprintf("select * %s limit %d, %d", baseSql, tqr.Page-1, tqr.PageSize)
		log.Infof("GetTagList: %v", limitSql)
		var res []models.Tag
		err := databases.GetDB().Raw(limitSql).Scan(&res).Error
		if err != nil {
			helper.SetHttpMsgResp(c, helper.HttpCodeInternalFail, errors.WithMessage(err, "db query fail").Error())
			return
		}
		var rows []TagInfoQueryResp
		for _, row := range res {
			tg := TagInfoQueryResp{
				ID:          row.ID,
				TagName:     row.TagName,
				CitedNum:    row.CitedNum,
				Description: row.Description,
			}
			rows = append(rows, tg)
		}
		resp := TagListQueryResp{
			Tags:         rows,
			Page:         tqr.Page,
			Count:        len(res),            // 记录总数
			TotalPageNum: len(res) / tqr.Page, // 总页数
		}
		data, _ := json.Marshal(resp)
		helper.SetHttpDataResp(c, string(data))
	}
}

func GetTagInfo() gin.HandlerFunc {
	return func(c *gin.Context) {
		tir := new(TagInfoQueryReq)
		if err := c.ShouldBindJSON(tir); err != nil {
			helper.SetHttpMsgResp(c, helper.HttpCodeValidateFail, helper.Translate(err))
			return
		}
		row, err := models.NewTag(nil).Where(&models.Tag{TagName: tir.TagLikeName}).First()
		if err != nil {
			helper.SetHttpMsgResp(c, helper.HttpCodeInternalFail, errors.WithMessage(err, "db query fail").Error())
			return
		}
		resp := TagInfoQueryResp{
			ID:          row.ID,
			TagName:     row.TagName,
			CitedNum:    row.CitedNum,
			Description: row.Description,
		}
		data, _ := json.Marshal(resp)
		helper.SetHttpDataResp(c, string(data))
	}
}
